package com.it.hanzhongtravelv1.controller;

import com.it.hanzhongtravelv1.dto.FoodDTO;
import com.it.hanzhongtravelv1.dto.RestaurantDTO;
import com.it.hanzhongtravelv1.entity.*;
import com.it.hanzhongtravelv1.repository.*;
import com.it.hanzhongtravelv1.service.FoodRecommendationService;
import com.it.hanzhongtravelv1.dto.TravelRouteDTO;
import com.it.hanzhongtravelv1.service.TravelRouteService;
import com.it.hanzhongtravelv1.service.AccommodationService;
import com.it.hanzhongtravelv1.dto.AccommodationDTO;
import com.it.hanzhongtravelv1.service.CulturalActivityService;
import com.it.hanzhongtravelv1.dto.CulturalActivityDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "*")
public class TravelController {
    
    @Autowired
    private AttractionRepository attractionRepository;
    
    @Autowired
    private FoodRepository foodRepository;
    
    @Autowired
    private TravelRouteRepository travelRouteRepository;
    
    @Autowired
    private TravelGuideRepository travelGuideRepository;
    
    @Autowired
    private CulturalActivityRepository culturalActivityRepository;
    
    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private FoodRecommendationService foodRecommendationService;
    
    @Autowired
    private TravelRouteService travelRouteService;
    
    @Autowired
    private AccommodationService accommodationService;
    
    @Autowired
    private CulturalActivityService culturalActivityService;
    
    // 景点相关API
    @GetMapping("/attractions")
    public List<Attraction> getAttractions() {
        return attractionRepository.findAll();
    }
    
    @GetMapping("/attractions/type/{category}")
    public List<Attraction> getAttractionsByCategory(@PathVariable String category) {
        return attractionRepository.findByCategory(category);
    }
    
    // 旅游线路API
    @GetMapping("/travel-routes")
    public List<TravelRouteDTO> getTravelRoutes() {
        return travelRouteService.getAllTravelRoutes();
    }
    
    @GetMapping("/travel-routes/{id}")
    public ResponseEntity<TravelRouteDTO> getTravelRouteById(@PathVariable Long id) {
        TravelRoute route = travelRouteRepository.findById(id).orElse(null);
        if (route != null) {
            return ResponseEntity.ok(travelRouteService.convertToTravelRouteDto(route));
        }
        return ResponseEntity.notFound().build();
    }
    
    @PostMapping("/travel-routes")
    public ResponseEntity<TravelRoute> createTravelRoute(@RequestBody TravelRoute route) {
        try {
            // 确保price字段正确处理
            if (route.getPrice() == null) {
                route.setPrice(0.0);
            }
            
            // 处理days关联关系
            if (route.getDays() != null) {
                for (RouteDay day : route.getDays()) {
                    day.setTravelRoute(route);
                    if (day.getActivities() != null) {
                        for (DayActivity activity : day.getActivities()) {
                            activity.setRouteDay(day);
                            // 处理timeType枚举转换
                            if (activity.getTimeType() == null && activity.getTime() != null) {
                                // 根据时间格式推断类型
                                String timeStr = activity.getTime();
                                if (timeStr.matches("\\d{2}:\\d{2}")) {
                                    activity.setTimeType(DayActivity.ActivityTimeType.TIME_POINT);
                                } else if (timeStr.contains("上午") || timeStr.contains("下午") || timeStr.contains("晚上")) {
                                    activity.setTimeType(DayActivity.ActivityTimeType.TIME_SLOT);
                                } else {
                                    activity.setTimeType(DayActivity.ActivityTimeType.DAILY_SUMMARY);
                                }
                            }
                        }
                    }
                }
            }
            
            TravelRoute savedRoute = travelRouteRepository.save(route);
            return ResponseEntity.ok(savedRoute);
        } catch (Exception e) {
            System.err.println("创建线路失败: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.badRequest().build();
        }
    }
    
    @PutMapping("/travel-routes/{id}")
    public ResponseEntity<TravelRoute> updateTravelRoute(@PathVariable Long id, @RequestBody TravelRoute route) {
        try {
            if (travelRouteRepository.existsById(id)) {
                route.setId(id);
                
                // 确保price字段正确处理
                if (route.getPrice() == null) {
                    route.setPrice(0.0);
                }
                
                // 处理days关联关系
                if (route.getDays() != null) {
                    for (RouteDay day : route.getDays()) {
                        day.setTravelRoute(route);
                        if (day.getActivities() != null) {
                            for (DayActivity activity : day.getActivities()) {
                                activity.setRouteDay(day);
                                // 处理timeType枚举转换
                                if (activity.getTimeType() == null && activity.getTime() != null) {
                                    // 根据时间格式推断类型
                                    String timeStr = activity.getTime();
                                    if (timeStr.matches("\\d{2}:\\d{2}")) {
                                        activity.setTimeType(DayActivity.ActivityTimeType.TIME_POINT);
                                    } else if (timeStr.contains("上午") || timeStr.contains("下午") || timeStr.contains("晚上")) {
                                        activity.setTimeType(DayActivity.ActivityTimeType.TIME_SLOT);
                                    } else {
                                        activity.setTimeType(DayActivity.ActivityTimeType.DAILY_SUMMARY);
                                    }
                                }
                            }
                        }
                    }
                }
                
                TravelRoute savedRoute = travelRouteRepository.save(route);
                return ResponseEntity.ok(savedRoute);
            }
            return ResponseEntity.notFound().build();
        } catch (Exception e) {
            System.err.println("更新线路失败: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.badRequest().build();
        }
    }
    
    @DeleteMapping("/travel-routes/{id}")
    public ResponseEntity<Void> deleteTravelRoute(@PathVariable Long id) {
        try {
            if (travelRouteRepository.existsById(id)) {
                travelRouteRepository.deleteById(id);
                return ResponseEntity.ok().build();
            }
            return ResponseEntity.notFound().build();
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }
    
    @GetMapping("/travel-routes/type/{duration}")
    public List<TravelRouteDTO> getTravelRoutesByDuration(@PathVariable String duration) {
        return travelRouteService.getTravelRoutesByDuration(duration);
    }
    
    // 旅游攻略API
    @GetMapping("/travel-guides")
    public List<TravelGuide> getTravelGuides() {
        return travelGuideRepository.findAll();
    }
    
    @GetMapping("/travel-guides/type/{category}")
    public List<TravelGuide> getTravelGuidesByCategory(@PathVariable String category) {
        return travelGuideRepository.findByCategory(category);
    }
    
    // 文化活动API - V1
    @GetMapping("/v1/cultural-activities")
    public List<CulturalActivityDTO> getAllCulturalActivities() {
        return culturalActivityService.getAllActivities();
    }
    
    // 用户相关API
    @PostMapping("/login")
    public ResponseEntity<Map<String, Object>> login(@RequestBody Map<String, String> credentials) {
        Map<String, Object> response = new HashMap<>();
        try {
            String username = credentials.get("username");
            String password = credentials.get("password");
            
            User user = userRepository.findByUsername(username).orElse(null);
            if (user != null && user.getPassword().equals(password)) {
                response.put("success", true);
                response.put("message", "登录成功");
                response.put("user", Map.of(
                    "id", user.getId(),
                    "username", user.getUsername(),
                    "email", user.getEmail()
                ));
            } else {
                response.put("success", false);
                response.put("message", "用户名或密码错误");
            }
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "登录失败：" + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    @PostMapping("/register")
    public ResponseEntity<Map<String, Object>> register(@RequestBody User user) {
        Map<String, Object> response = new HashMap<>();
        try {
            if (userRepository.existsByUsername(user.getUsername())) {
                response.put("success", false);
                response.put("message", "用户名已存在");
                return ResponseEntity.badRequest().body(response);
            }
            if (userRepository.existsByEmail(user.getEmail())) {
                response.put("success", false);
                response.put("message", "邮箱已被注册");
                return ResponseEntity.badRequest().body(response);
            }
            
            userRepository.save(user);
            response.put("success", true);
            response.put("message", "注册成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "注册失败：" + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
} 